/**
 * 
 */
package com.vector.ding.web.service.baseinfo;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.vector.ding.commons.BizConstant;
import com.vector.ding.commons.util.BeanUtil;
import com.vector.ding.commons.util.NumberUtil;
import com.vector.ding.commons.util.StringUtil;
import com.vector.ding.commons.util.collection.CollectionUtil;
import com.vector.ding.commons.util.file.ExcelUtil;
import com.vector.ding.commons.util.web.RequestUtil;
import com.vector.ding.dao.mybatis.mapper.GqtzgsBaseInfoMapper;
import com.vector.ding.dao.mybatis.model.GqtzgsBaseInfo;
import com.vector.ding.dao.mybatis.model.GqtzgsBaseInfoExample;
import com.vector.ding.exception.BaseException;

/**
 * @author vector
 *
 */
@Service
public class GqtzgsBaseInfoMgrService {
	
	private static Logger logger = LoggerFactory.getLogger(GqtzgsBaseInfoMgrService.class);

	@Autowired
	private GqtzgsBaseInfoMapper baseMapper;
	
	public GqtzgsBaseInfo getBaseInfo(String number) {
		return baseMapper.selectByPrimaryKey(number);
	}
	
	public GqtzgsBaseInfo getBaseInfoByName(String companyName) {
		GqtzgsBaseInfoExample example = new GqtzgsBaseInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		List<GqtzgsBaseInfo> list = baseMapper.selectByExample(example);
		return CollectionUtil.isEmpty(list) ? null : list.get(0);
	}
	
	public List<GqtzgsBaseInfo> getBaseInfo(int pageIndex, int pageSize, 
			HttpServletRequest request) {
		if (pageSize != Integer.MAX_VALUE)
			PageHelper.startPage(pageIndex, pageSize, true);
		GqtzgsBaseInfoExample example = getBaseInfoExample(request);
		//example.setOrderByClause("number asc");
		return baseMapper.selectByExample(example);
	}
	
	private GqtzgsBaseInfoExample getBaseInfoExample(HttpServletRequest request) {
		GqtzgsBaseInfoExample example = new GqtzgsBaseInfoExample();
		String companyName = StringUtil.getString(request.getParameter("company_name")).trim();
		//if (StringUtil.isNotEmpty(companyName))
		example.or().andCompanyNameLike(StringUtil.wrapString(companyName, "%", "%"));
		return example;
	}
	
	public GqtzgsBaseInfo getBaseInfoBean(HttpServletRequest request) {
		Map<String, Object> paramMap = RequestUtil.getParamMap(request);
		Set<String> excludeProSet = CollectionUtil.asSet(
				"registerFundRmb", "registerFundDollar");
		GqtzgsBaseInfo baseInfo = new GqtzgsBaseInfo();
		BeanUtil.fillBeanProperty(paramMap, baseInfo, excludeProSet);
		baseInfo.setRegisterFundRmb(NumberUtil.getBigDecimal(paramMap.get("registerFundRmb")));
		baseInfo.setRegisterFundDollar(NumberUtil.getBigDecimal(paramMap.get("registerFundDollar")));
		if (StringUtil.isEmpty(baseInfo.getNumber()))
			baseInfo.setNumber(StringUtil.getUuid());
		
		return baseInfo;
	} 
	
	public void importFormFile(File importFile) {
		HSSFWorkbook workBook = null;
		int rowIndex = 1;
		try {
			workBook = new HSSFWorkbook(FileUtils.openInputStream(importFile));
			HSSFSheet sheet = workBook.getSheetAt(0);
			HSSFRow titleRow = sheet.getRow(0);
			for (int cellIdx = titleRow.getFirstCellNum(); cellIdx < titleRow.getLastCellNum(); ++cellIdx) {
				System.out.println(titleRow.getCell(cellIdx).toString());
			}
			int rowNum = sheet.getLastRowNum();
			for (rowIndex = 1; rowIndex <= rowNum; ++rowIndex) {
				HSSFRow row = sheet.getRow(rowIndex);
				boolean needImport = checkRowData(row);
				if (!needImport)
					continue;
				
				GqtzgsBaseInfo bean = getBaseInfoBean(row);
				baseMapper.insertSelective(bean);
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException(String.format("第%s行数据格式有误，请检查数据！", rowIndex));
		} finally {
			if (workBook != null) {
				try {
					workBook.close();
				} catch (IOException e) {
					e.printStackTrace();
					throw new BaseException(e);
				}
			}
		}
	}
	
	public GqtzgsBaseInfo getBaseInfoBean(HSSFRow row) {
		DecimalFormat df = new DecimalFormat("0");
		GqtzgsBaseInfo bean = new GqtzgsBaseInfo();
		bean.setNumber(StringUtil.getUuid());
//		bean.setNumber(ExcelUtil.getStringValue(row.getCell(BizConstant.Gqtzgs.Base.NUMBER_CELL), true));
		bean.setAcceptOffice(ExcelUtil.getRowCellStringValue(row, BizConstant.Gqtzgs.Base.AC_OFFICE_CELL));
		bean.setAddress(row.getCell(BizConstant.Gqtzgs.Base.ADDRESS_CELL).toString());
		bean.setBelongArea(row.getCell(BizConstant.Gqtzgs.Base.BELONG_AREA_CELL).toString());
		bean.setBusinessType(row.getCell(BizConstant.Gqtzgs.Base.BUSINESS_TYPE_CELL).toString());
		bean.setCompanyMark(row.getCell(BizConstant.Gqtzgs.Base.COMPANY_MARK_CELL).toString());
		bean.setCompanyName(row.getCell(BizConstant.Gqtzgs.Base.COMPANY_NAME_CELL).toString());
		bean.setCompanyType(row.getCell(BizConstant.Gqtzgs.Base.COMPANY_TYPE_CELL).toString());
		bean.setDelegateName(row.getCell(BizConstant.Gqtzgs.Base.DELEGATE_PEOPLE_CELL).toString());
		bean.setEstablishDate(ExcelUtil.getDateString(row.getCell(BizConstant.Gqtzgs.Base.ESTABLISH_DATE_CELL)));
		bean.setLocationStreet(row.getCell(BizConstant.Gqtzgs.Base.LOCATION_STREET_CELL).toString());
		bean.setRegisterFundDollar(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Base.REG_FUND_DOLLAR_CELL).getNumericCellValue()));
		bean.setRegisterFundRmb(new BigDecimal(row.getCell(BizConstant.Gqtzgs.Base.REG_FUND_RMB_CELL).getNumericCellValue()));
		bean.setRegisterNumber(row.getCell(BizConstant.Gqtzgs.Base.REG_NUM_CELL).toString());
		HSSFCell telCell = row.getCell(BizConstant.Gqtzgs.Base.TEL_CELL);
		if (telCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
			bean.setTelephone(StringUtil.getString(df.format(telCell.getNumericCellValue())));
		} else {
			bean.setTradeType(telCell.toString());
		}
//		double tel = row.getCell(BizConstant.Gqtzgs.Base.TEL_CELL).getNumericCellValue();
//		String telString = df.format(tel);
//		bean.setTelephone(telString);
		HSSFCell cell = row.getCell(BizConstant.Gqtzgs.Base.TRADE_TYPE_CELL);
		if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
			bean.setTradeType(StringUtil.getString((int)cell.getNumericCellValue()));
		} else {
			bean.setTradeType(cell.toString());
		}
		
		return bean;
	}
	
	private boolean checkRowData(HSSFRow row) {
		String number = StringUtil.getString((int)row.getCell(BizConstant.Gqtzgs.Base.NUMBER_CELL).getNumericCellValue());
		String companyName = row.getCell(BizConstant.Gqtzgs.Base.COMPANY_NAME_CELL).toString();
		if (StringUtil.isEmpty(number))
			return false;
		
		GqtzgsBaseInfoExample example = new GqtzgsBaseInfoExample();
		example.or().andNumberEqualTo(number);
		example.or().andCompanyNameEqualTo(companyName);
		return baseMapper.countByExample(example) == 0;
	}

	public int delete(String[] ids) {
		if (ids == null || ids.length == 0)
			return 0;
		
		int count = 0;
		for (String id: ids) {
			count += baseMapper.deleteByPrimaryKey(id);
		}
		return count;
	}

	public boolean updateBaseInfo(GqtzgsBaseInfo baseInfo) {
		int cnt = baseMapper.updateByPrimaryKeySelective(baseInfo);
		if (cnt == 0) {
			logger.error("更新股权投资公司基本信息记录失败：未找到number为{}的记录...", baseInfo.getNumber());
		}
			
		return cnt != 0 ? true : false;
	}

	public boolean insertBaseInfo(GqtzgsBaseInfo baseInfo) {
		int cnt = 0;
		try {
			cnt = baseMapper.insertSelective(baseInfo);
		} catch (Exception e) {
			if (logger.isDebugEnabled())
				e.printStackTrace();
		}
		if (cnt == 0) {
			logger.error("插入股权投资公司基本信息记录失败：number为{}...", baseInfo.getNumber());
		}
			
		return cnt != 0 ? true : false;
	}
	
	public boolean existsCompany(String companyName) {
		GqtzgsBaseInfoExample example = new GqtzgsBaseInfoExample();
		example.or().andCompanyNameEqualTo(companyName);
		return baseMapper.countByExample(example) > 0 ? true : false;
	}
}
